﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using DSAServer.Models;
using DSAServer.Models.Input;
using DSAServer.Models.Output;
using DSAServer.Service;
using DSAServer.Utils;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.QrCode;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MvcExtension;
using SunyuCRM.API.Weixin.CommonService.CustomMessageHandler;

namespace DSAServer.Controllers
{
    public class WeixinController : BaseController
    {
        public static readonly string Token = WebConfigurationManager.AppSettings["WeixinToken"];//与微信公众账号后台的Token设置保持一致，区分大小写。
        public static readonly string EncodingAESKey = WebConfigurationManager.AppSettings["WeixinEncodingAESKey"];//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string AppId = WebConfigurationManager.AppSettings["WeixinAppId"];//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string AppSecret = WebConfigurationManager.AppSettings["WeixinAppSecret"];

        readonly Func<string> _getRandomFileName = () => DateTime.Now.Ticks + Guid.NewGuid().ToString("n").Substring(0, 6);

        //[HttpGet]
        //[ActionName("Index")]
        //public ActionResult Index(PostModel postModel, string echostr)
        //{
        //    //string echoString = HttpContext.Request.QueryString["echostr"];
        //    //string signature = HttpContext.Request.QueryString["signature"];
        //    //string timestamp = HttpContext.Request.QueryString["timestamp"];
        //    //string nonce = HttpContext.Request.QueryString["nonce"];
        //    LogUtil.Error("get", null);
        //    if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
        //    {
        //        return Content(echostr); //返回随机字符串则表示验证通过
        //    }
        //    else
        //    {
        //        return Content("failed:" + postModel.Signature + "," + CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
        //            "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。");
        //    }
        //}

        //[HttpPost]
        //[ActionName("Index")]
        public ActionResult Index()//PostModel postModel
        {
            //LogUtil.Error(this.Request.QueryString.ToString(), null);
            //LogUtil.Error(this.Request.Headers.ToString(), null);
            //LogUtil.Error("HttpMethod:" + this.Request.HttpMethod.ToUpper(), null);

            string echoString = this.Request.QueryString["echostr"];
            string signature = this.Request.QueryString["signature"];
            string timestamp = this.Request.QueryString["timestamp"];
            string nonce = this.Request.QueryString["nonce"];
            //LogUtil.Error("this.Request.QueryString获取参数" + "Signature：" + signature + "|Timestamp：" + timestamp + "|Nonce：" + nonce + "|Token：" + Token + "|AppId：" + AppId + "|AppSecret：" + AppSecret, null);
            PostModel postModel = new PostModel()
            {
                AppId = AppId,
                EncodingAESKey = EncodingAESKey,
                Nonce = nonce,
                Signature = signature,
                Timestamp = timestamp,
                Token = Token
            };

            if (this.Request.HttpMethod.ToUpper() == "POST")
            {
                string postString = "";
                try
                {
                    var maxRecordCount = 10;
                    //var messageHandler = new CustomMessageHandler(postString, maxRecordCount);
                    var messageHandler = new CustomMessageHandler(this.Request.InputStream, postModel, maxRecordCount);
                    messageHandler.Execute();
                    return new WeixinResult(messageHandler);//v0.8+
                }
                catch (Exception ex)
                {
                    LogUtil.Error("微信消息处理出错", ex);
                    return Content("");
                }

                return Content("");
            }
            else
            {
                //var temp = CheckSignature.GetSignature(timestamp, nonce, Token);
                //LogUtil.Error("签名：" + temp, null);
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    //LogUtil.Error("token校验正确", null);
                    return Content(echoString); //返回随机字符串则表示验证通过
                }
                else
                {
                    //LogUtil.Error("token校验出错", null);
                    return Content("");
                }
            }
        }

        public ActionResult CreateQrCode()
        {
            var data = getRequestData<QrCodeParaInfo>();
            InvokeResult<CreateQrCodeResult> result = new InvokeResult<CreateQrCodeResult>();
            var weixinService = new WeixinService();
            result = weixinService.CreateQrCode(AppId, AppSecret, data);
            return Content(JsonHelper.SerializeObject(result));
        }

        public ActionResult CreateByStr()
        {
            var data = getRequestData<string>();
            InvokeResult<CreateQrCodeResult> result = new InvokeResult<CreateQrCodeResult>();
            var weixinService = new WeixinService();
            result = weixinService.CreateByStr(AppId, AppSecret, data);
            return Content(JsonHelper.SerializeObject(result));
        }

        /// <summary>
        /// 创建微信菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateWeixinMenu()
        {
            //InvokeDataResult<WxJsonResult> result = new InvokeDataResult<WxJsonResult>();
            //var weixinService = IoC.Resolve<IWeixinService>();
            //result = weixinService.CreateMenu(AppId, AppSecret);
            //return result;
            InvokeResult<WxJsonResult> result = new InvokeResult<WxJsonResult>();
            var weixinService = new WeixinService();
            result = weixinService.CreateMenu(AppId, AppSecret);
            return Content(JsonHelper.SerializeObject(result));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult WeiShopOrder()
        {
            if (this.Request.HttpMethod.ToUpper() == "POST")
            {
                string postString = "";
                using (Stream stream = this.Request.InputStream)
                {
                    Byte[] postBytes = new Byte[stream.Length];
                    stream.Read(postBytes, 0, (Int32)stream.Length);
                    postString = Encoding.UTF8.GetString(postBytes);
                }
                //LogUtil.Info("POST:" + postString);
                postString = HttpUtility.UrlDecode(postString);
                LogUtil.Info("POST:" + postString);
                try
                {
                    if (!string.IsNullOrEmpty(postString) && postString.Length > 8)
                    {
                        postString = postString.Remove(0, 8);
                        var objTemp = JsonHelper.DeserializeObject<Rootobject>(postString);
                        if (objTemp != null)
                        {
                            switch (objTemp.type)
                            {
                                case "weidian.order.already_payment"://已付款
                                    bool flag = false;
                                    TradeInfo tradeInfo = new TradeInfo()
                                    {
                                        buyernick = objTemp.message.buyer_info.name,
                                        buyermessage = "",
                                        created = Convert.ToDateTime(objTemp.message.add_time),
                                        downloadtime = null,
                                        hasdownload = false,
                                        hassend = false,
                                        hasupload = false,
                                        no = objTemp.message.order_id,
                                        receiveraddress = objTemp.message.buyer_info.address,
                                        receivermobile = objTemp.message.buyer_info.phone,
                                        receivername = objTemp.message.buyer_info.name,
                                        sendtime = null,
                                        source = 1,
                                        status = objTemp.type,
                                        totalfee = Convert.ToDecimal(objTemp.message.total)
                                    };
                                    List<Models.Input.OrderInfo> orderList = new List<Models.Input.OrderInfo>();
                                    //检测订单产品是否需要冲洗
                                    var printList = ConfigUtils<PrintList>.Instance("printlist");
                                    var bigpictureList = ConfigUtils<BigPicturePrintList>.Instance("bigpictureprintlist");
                                    var otherprintList = ConfigUtils<OtherPrintList>.Instance("otherprintlist");

                                    foreach (Item item in objTemp.message.items)
                                    {
                                        var needprint = printList.Find((PrintList pl) => item.item_name.Contains(SubstringProductName(pl.name)));
                                        if (needprint != null)//属于要冲洗的产品
                                        {
                                            flag = true;
                                            //LogUtil.Info("SKU：" + item.sku_title);
                                            var size = "8寸";
                                            if (!string.IsNullOrEmpty(item.sku_title))
                                                size = RegexSku(item.sku_title);
                                            var producttype = "普通照片";
                                            if (item.item_name.Contains("拍立得"))
                                                producttype = "拍立得";
                                            else if (item.item_name.Contains("正方形"))
                                                producttype = "正方形";
                                            else
                                                producttype = "普通照片";

                                            var uploadtype = 0;//上传通道
                                            var bigpicture = bigpictureList.Find((BigPicturePrintList bppl) => item.item_name.Contains(SubstringProductName(bppl.name)));
                                            var s = 0;
                                            if (bigpicture != null)
                                            {
                                                LogUtil.Info("SIZE:" + size);
                                                Int32.TryParse(size.Replace("寸", "").Replace("大", ""), out s);
                                                LogUtil.Info("计算图片上传通道" + s + "配置大小" + bigpicture.size);
                                                if (s >= bigpicture.size)
                                                    uploadtype = 1;
                                            }

                                            var quantity = item.quantity;//计算数量
                                            var otherPrint = otherprintList.Find((OtherPrintList opl) => item.item_name.Contains(SubstringProductName(opl.name)));
                                            if (otherPrint != null)
                                            {
                                                quantity = (Convert.ToInt32(item.quantity) * otherPrint.num).ToString();
                                            }
                                            LogUtil.Info("换算完成");
                                            Models.Input.OrderInfo orderInfo = new Models.Input.OrderInfo();
                                            orderInfo.createtime = Convert.ToDateTime(objTemp.message.add_time);
                                            LogUtil.Info("1");
                                            orderInfo.downloadtime = null;
                                            orderInfo.hasdownload = false;
                                            orderInfo.num = quantity;
                                            LogUtil.Info("2");
                                            orderInfo.oid = Guid.NewGuid().ToString().Replace("-", "");
                                            orderInfo.ono = objTemp.message.order_id;
                                            orderInfo.packagetype = "";//冷表过塑
                                            LogUtil.Info("3");
                                            orderInfo.payment = item.total_price;
                                            orderInfo.picpaper = !string.IsNullOrEmpty(item.sku_title) ? item.sku_title.Replace(size, "") : "";//材质
                                            orderInfo.producttype = producttype;//照片类型
                                            LogUtil.Info("4");
                                            orderInfo.skupropertiesname = size;//尺寸
                                            orderInfo.source = 1;
                                            orderInfo.status = "";
                                            LogUtil.Info("5");
                                            orderInfo.title = item.item_name;
                                            orderInfo.uploadtype = uploadtype;//上传通道
                                            orderInfo.imgurl = item.img;
                                            LogUtil.Info("6");
                                            orderList.Add(orderInfo);
                                        }
                                    }
                                    if (flag)
                                    {
                                        LogUtil.Info("操作数据库");
                                        OrderService orderService = new OrderService();
                                        orderService.InsertWeidianOrder(tradeInfo, orderList);
                                    }
                                    break;
                                case "weidian.order.delivered"://已发货，更改订单状态为不可上传状态
                                    OrderService orderService1 = new OrderService();
                                    var no = objTemp.message.order_id;
                                    orderService1.UpdateTrade(no);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.Info(ex.Message + ex.Source + ex.StackTrace);
                }
            }
            else
            {
                string getString = "";
                foreach (string str in this.Request.QueryString.AllKeys)
                {
                    getString += str + ":" + Request.QueryString[str];
                }
                LogUtil.Info("GET" + getString);
            }
            return Content("ok");
        }

        public ActionResult QueryUnUploadOrderInfoByMobile()
        {
            var data = getRequestData<string>();
            var result = new OrderService().QueryUnUploadOrderInfoByMobile(data);
            return Content(JsonHelper.SerializeObject(result));
        }

        public ActionResult SumbitOrderInfo()
        {
            var data = getRequestData<List<OrderDetail>>();
            var result = new OrderService().SumbitOrderInfo(data);
            LogUtil.Info("数据库操作回执" + JsonHelper.SerializeObject(result));
            return Content(JsonHelper.SerializeObject(result));
        }


        private string SubstringProductName(string name)
        {
            string result = "";
            if (name.Length > 18)
            {
                result = name.Substring(0, 18);
            }
            else
                result = name;
            return result;
        }

        private string RegexSku(string str)
        {
            Regex reg = new Regex(@"\d*寸|大\d*寸");
            return reg.Match(str).Value;
        }
    }
}